package com.ailink.concurrent.thread.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Created by Administrator on 2018/9/27
 */
@Slf4j
public class ThreadPoolTest {

    public static class RunnableTask implements Runnable {
        private int id;
        public RunnableTask(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread() + " " + "执行任务 " + String.valueOf(id));
            try {
                Thread.sleep(1000 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
            4,
                1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(16),
                new ThreadFactoryTask(),
                new ThreadPoolExecutor.AbortPolicy());
        threadPoolExecutor.prestartAllCoreThreads();
        for (int i = 0; i < 100; i++) {
            try {
                threadPoolExecutor.execute(new RunnableTask(i));
            } catch (Exception e) {
                System.out.println(e);
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        threadPoolExecutor.shutdown();
        try {
            Thread.sleep(1000 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
